#include <stdio.h>
#include <sys/shm.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>

int main(int argc,char* argv[])
{
    if(argc != 2)
    {
        return -1;
    }
    
    // 唯一的 key_t
    key_t key = ftok("./",0x6);
    if(key ==-1)
    {
        perror("ftok reeoe ");
        return -1;
    }

    // 1. 创建共享内存, 大小为4k
    int shmid = shmget(key, 0, 0);
    if(shmid == -1)
    {
        perror("shmget error ");
        return -1;
    }

    // 2. 当前进程和共享内存关联
    void* ptr = shmat(shmid, NULL, 0);
    if(ptr == (void *) -1)
    {
        perror("shmat error");
        goto clear;
    }
    
    FILE* write_p=fopen(argv[1],"w+");
    if(write_p == NULL)
    {
        perror("fopen error");
        goto clear;
    }

    fwrite(ptr,sizeof(char),strlen((char*)ptr),write_p);

    // 阻塞程序
    printf("按任意键继续, 删除共享内存\n");
    getchar();
    
    // 共享内存和当前进程分离
clear:shmdt(ptr);

    // 删除共享内存
    shmctl(shmid, IPC_RMID, NULL);
    printf("共享内存已经被删除...\n");

    return 0;
}

